package com.bear.fastrepair.utils

import android.graphics.Color
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

/**
 * @description
 * @author jacky
 * @date 2021/11/17-16:21
 */

/**
 * viewmodel协程启动器，注意异常捕获必须在顶层协程进行处理，子协程处理异常依然会向上抛出
 * @receiver ViewModel
 * @param onError Function1<[@kotlin.ParameterName] Throwable, Unit>
 * @param onComplete Function0<Unit>
 * @param block [@kotlin.ExtensionFunctionType] SuspendFunction1<CoroutineScope, Unit>
 */
fun ViewModel.launch(
    onError: (e: Throwable) -> Unit = {
        it.printStackTrace()
        Log.e(javaClass.simpleName, "view model launch error: ${it.message}")
    },
    onComplete: () -> Unit = {},
    block: suspend CoroutineScope.() -> Unit
) {
    viewModelScope.launch(CoroutineExceptionHandler { _, throwable -> onError(throwable) }) {
        try {
            block()
        } finally {
            onComplete()
        }
    }
}

fun Fragment.setSystemUIHide() {
    val decorView = requireActivity().window.decorView
    val option = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
            View.SYSTEM_UI_FLAG_FULLSCREEN or
            View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
    decorView.systemUiVisibility = option
}

fun Fragment.setSystemUIShow() {
    val decorView = requireActivity().window.decorView
    val option = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE
    decorView.systemUiVisibility = option
}

fun Fragment.setBarTransparent() {
    setSystemUIShow()
    requireActivity().window.let {
        it.navigationBarColor = Color.TRANSPARENT
        it.statusBarColor = Color.TRANSPARENT
    }
}